<?php

namespace app\admin\controller\activityform;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * 用户表单数据
 *
 * @icon fa fa-circle-o
 */
class Fromurldata extends Backend
{
    /**
     * Fromurldata模型对象
     * @var \app\admin\model\Fromurldata
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activityform\Fromurldata;
    }

    // 导出方法
    public function export($id)
    {
        // 获取数据
        $data = $this->model->getNameofColumn($id);

        // 判断数据是否为空
        if (empty($data)) {
            // 数据为空时，输出提示信息并结束函数执行
            $this->error('没有数据可以导出');
        }
        ini_set('memory_limit', '2560M');
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 固定表头
        $tableHeader = ['序号', '姓名', '微信号', '手机号', '创建时间'];

        // 获取动态表头（来自 customdata）
        $dynamicHeaders = $this->getCustomDataHeader($id);
        $tableHeader = array_merge($tableHeader, $dynamicHeaders); // 合并固定和动态表头

        // 设置样式
        $styleArray = [
            'font' => [
                'bold' => true,
                'color' => ['rgb' => 'FFFFFF'],
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
                'wrapText' => true,  // 启用自动换行
            ],
        ];

        // 设置表头区域
        $headerRange = 'A1:' . chr(64 + count($tableHeader)) . '1'; // 动态设置表头范围
        $sheet->getStyle($headerRange)->applyFromArray($styleArray);

        // 设置表头背景色
        $fill = $sheet->getStyle($headerRange)->getFill();
        $fill->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('4169DD');

        // 设置表头居中
        $alignment = $sheet->getStyle($headerRange)->getAlignment();
        $alignment->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // 设置列宽
        $sheet->getDefaultColumnDimension()->setWidth(17);
        $column = 'A';
        foreach ($tableHeader as $header) {
            $sheet->setCellValue($column . '1', $header);
            $column++;
        }


        // 获取数据
        $data = $this->model->getNameofColumn($id);
        $row = 2;
        $dataStyle = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,  // 水平居中对齐
                'vertical' => Alignment::VERTICAL_CENTER,      // 垂直居中对齐
                'wrapText' => true,  // 启用自动换行
            ],
        ];
        foreach ($data as $rowData) {
            $column = 'A';
            foreach ($rowData as $key => $value) {
                if ($key == 'customdata') {
                    // 处理 customdata 字段
                    $customData = json_decode($value, true);
                    foreach ($customData as $item) {
                        foreach ($item as $subKey => $subValue) {
                            // 如果值是数组，转换为字符串
                            if (is_array($subValue)) {
                                // 将数组转换为字符串（可以使用逗号、换行符等作为分隔符）
                                $subValue = implode("\n", $subValue);  // 使用换行符连接数组元素
                            }
                            // 写入值
                            if (!is_array($subValue)) {
                                $sheet->setCellValue($column . $row, $subValue);
                                $sheet->getStyle($column . $row)->applyFromArray($dataStyle);  // 应用数据样式
                                $column++;
                            } else {
                                // 如果是数组，处理多选项
                                foreach ($subValue as $subVal) {
                                    if ($this->isImageLink($subVal)) {
                                        // 如果是图片链接，插入图片
                                        $imageStream = file_get_contents($subVal);
                                        $gdImage = imagecreatefromstring($imageStream);
                                        if ($gdImage !== false) {
                                            $drawing = new MemoryDrawing();
                                            $drawing->setResizeProportional(false);
                                            $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG);
                                            $drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT);
                                            $drawing->setImageResource($gdImage);
                                            $drawing->setWidth(110);
                                            $drawing->setHeight(110);
                                            $drawing->setOffsetX(5);
                                            $drawing->setOffsetY(5);
                                            $drawing->setCoordinates($column . $row);
                                            $drawing->setWorksheet($spreadsheet->getActiveSheet());

                                            // 调整列宽和行高
                                            $sheet->getColumnDimension($column)->setWidth(17);
                                            $sheet->getRowDimension($row)->setRowHeight(90);
                                        }
                                    } else {
                                        // 如果是普通文本值
                                        $sheet->setCellValue($column . $row, $subVal);
                                    }
                                    $column++;
                                }
                            }
                        }
                    }
                } else {
                    if ($key == 'createtime') {
                        // 处理时间戳
                        $value = date('Y-m-d H:i:s', $value);
                    }
                    // 写入数据
                    $sheet->setCellValue($column . $row, $value);
                    $sheet->getStyle($column . $row)->applyFromArray($dataStyle);  // 应用数据样式
                    $column++;
                }
            }
            // 自动调整行高
            $sheet->getRowDimension($row)->setRowHeight(-1);  // 让行高自适应内容
            $row++;
        }

        // 获取问卷标题
        $fromurlM = new \app\admin\model\activityform\Fromurl;
        $title = $fromurlM->where('id', $id)->value('title');

        // 保存文件
        $writer = new Xlsx($spreadsheet);
        $filename = $title . '_' . date('Y年m月d日H时i分') . '数据.xlsx';

        // 输出文件到浏览器
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        // 输出到浏览器
        $writer->save('php://output');

        return;
    }

    // 获取 customdata 的表头
    private function getCustomDataHeader($id)
    {
        // 假设 getNameofColumn 方法可以获取该 ID 的数据
        $data = $this->model->getNameofColumn($id);
        $customData = json_decode($data[0]['customdata'], true); // 假设返回的是一个 JSON 字符串

        // 提取一级表头
        $headers = [];
        foreach ($customData as $item) {
            foreach ($item as $key => $value) {
                $headers[] = $key; // 只获取一级的键
            }
        }
        return $headers;
    }
    // 判断是否为图片链接
    private function isImageLink($url)
    {
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $fileExtension = pathinfo($url, PATHINFO_EXTENSION);
        return in_array(strtolower($fileExtension), $imageExtensions);
    }



    public function detail($ids, $datahref)
    {
        $list = $this->model->getNameofall($ids);

        foreach ($list as &$v) {
            $v['datahref'] = $datahref . $v['id'];
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        }
        unset($v);

        $this->view->assign("list", $list);

        return $this->view->fetch();
    }

    public function customData($id)
    {
        $list = $this->model->where('id', $id)->find();

        $this->view->assign("customData", json_decode($list['customdata'], true));
        $this->view->assign("phone", $list['phone']);

        return $this->view->fetch('customData');
    }
}
